package com.job;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.common.utils.AreaUtil;
import com.common.utils.DateUtils;
import com.common.utils.PythonUtils;
import com.common.utils.SysConfig;
import com.model.domain.device.GetDevicePcbBaseInfoDO;
import com.model.domain.device.GetDevicePcbGpsInfoDO;
import com.model.pojo.device.DevicePcbBaseInfo;
import com.model.pojo.device.DevicePcbDayInfo;
import com.model.pojo.device.DevicePcbGpsInfo;
import com.model.pojo.device.DevicePcbWorkDailyRecordInfo;
import com.service.activemq.MessageSenderService;
import com.service.device.DevicePcbBaseInfoService;
import com.service.device.DevicePcbDayInfoService;
import com.service.device.DevicePcbGpsInfoService;
import com.service.device.DevicePcbWorkDailyRecordInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @Description
 * @Author tm
 * @Date 2023-05-25 22:22
 **/
@Slf4j
@Component
@RequiredArgsConstructor
public class DevicePcbJob {
    private final DevicePcbGpsInfoService devicePcbGpsInfoService;
    private final DevicePcbDayInfoService devicePcbDayInfoService;
    private final DevicePcbBaseInfoService devicePcbBaseInfoService;
    private final DevicePcbWorkDailyRecordInfoService devicePcbWorkDailyRecordInfoService;
    private final MessageSenderService messageSenderService;
    /**
     * 统计每天的GPS信息
     *
     * @author tm
     * @date 2023-05-25 22:23
     */
    //使用
    @Scheduled(cron = "0 0 2 * * ?")
    public void countEveryDayGpsInfo() {
        if(SysConfig.getJobSwitch()==0)return;
        Date date = new Date();
        for (int i = 1; i < 2; i++) {
            List<DevicePcbDayInfo> dayList = new ArrayList<>();
            String tableName = "device_pcb_gps_info_";
            date = DateUtils.addDays(date, -1);
            int year = Integer.parseInt(DateUtils.getYear(date));
            int month = Integer.parseInt(DateUtils.getMonth(date));
            int day = Integer.parseInt(DateUtils.getDate(date));
            String dayStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date);
            dayStr = dayStr.replaceAll("-", "");
            GetDevicePcbGpsInfoDO getDevicePcbGpsInfoDO = new GetDevicePcbGpsInfoDO();
            getDevicePcbGpsInfoDO.setTableName(tableName + dayStr);
            List<Map<String, Object>> list = devicePcbGpsInfoService.getListGroupBy(getDevicePcbGpsInfoDO);
            if (list != null && list.size() > 0) {
                list.forEach(item -> {
                    String dtu = (String) item.get("dtu");
                    DevicePcbDayInfo dayInfo = new DevicePcbDayInfo();
                    dayInfo.setDtu(dtu);
                    dayInfo.setYear(year);
                    dayInfo.setMonth(month);
                    dayInfo.setDay(day);
                    dayInfo.setCreatedTime(new Date());
                    dayList.add(dayInfo);
                });
            }

            if (dayList != null && dayList.size() > 0) {
                devicePcbDayInfoService.saveList(dayList);
            }
        }
    }

    /**
     * 更新PCB设备的在线状态
     *
     * @author tm
     * @date 2023-05-27 10:10
     */
    //使用
    @Scheduled(cron = "0 */1 * * * ?")
    public void updatePcbOnLineStatus() {
        if(SysConfig.getJobSwitch()==0)return;
        GetDevicePcbBaseInfoDO getDevicePcbBaseInfoDO = new GetDevicePcbBaseInfoDO();
        getDevicePcbBaseInfoDO.setSortRow("createTime");
        getDevicePcbBaseInfoDO.setSortOrder("desc");
        List<DevicePcbBaseInfo> baseList = devicePcbBaseInfoService.getAllList(getDevicePcbBaseInfoDO);
        List<DevicePcbBaseInfo> updateBaseList = new ArrayList<>();
        if (baseList != null && baseList.size() > 0) {
            for (DevicePcbBaseInfo baseInfo : baseList) {
                int onLineStatus = 1;//在线状态，0离线，1在线
                if (baseInfo.getDataTime() != null) {
                    String time1 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date());
                    String time2 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, baseInfo.getDataTime());
                    List<Long> list = DateUtils.getDistanceTime(time1, time2);
                    if (list.get(0) > 0 || list.get(1) > 0 || list.get(2) > 2) onLineStatus = 0;
                } else {
                    onLineStatus = 0;
                }
                if (baseInfo.getOnLineStatus() == null || onLineStatus != baseInfo.getOnLineStatus()) {
                    baseInfo.setOnLineStatus(onLineStatus);
                    updateBaseList.add(baseInfo);
                }
            }
            if (updateBaseList.size() > 0) {
                devicePcbBaseInfoService.updateList(updateBaseList);
            }
            System.out.println("PCB在线状态更新完成");
        }
    }

//    @Scheduled(cron = "0 0 2 * * ?")
    public void calWorkArea() {
        Date date = new Date();
        for (int i = 1; i < 2; i++) {
            try {
                List<DevicePcbDayInfo> dayList = new ArrayList<>();
                String tableName = "device_pcb_gps_info_";
                date = DateUtils.addDays(date, -1);
                String dayStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date);
                dayStr = dayStr.replaceAll("-", "");
                GetDevicePcbGpsInfoDO getDevicePcbGpsInfoDO = new GetDevicePcbGpsInfoDO();
                getDevicePcbGpsInfoDO.setTableName(tableName + dayStr);
                List<Map<String, Object>> list = devicePcbGpsInfoService.getListGroupBy(getDevicePcbGpsInfoDO);
                if (list != null && list.size() > 0) {
                    List<DevicePcbWorkDailyRecordInfo> recordList = new ArrayList<>();
                    for (int j = 0; j < list.size(); j++) {
                        Map<String, Object> item = list.get(j);
                        DevicePcbWorkDailyRecordInfo recordInfo = new DevicePcbWorkDailyRecordInfo();
                        double area = 0;
                        String dtu = (String) item.get("dtu");
                        getDevicePcbGpsInfoDO.setDtu(dtu);
                        getDevicePcbGpsInfoDO.setSortRow("time");
                        getDevicePcbGpsInfoDO.setSortOrder("asc");
                        List<DevicePcbGpsInfo> gpsList = devicePcbGpsInfoService.getAllList(getDevicePcbGpsInfoDO);
                        if (gpsList != null && gpsList.size() > 0) {
                            String workType = gpsList.get(0).getBizCode();
                            area = new AreaUtil().handleTrack(gpsList, 2,workType);//默认幅宽为2000
                        }
                        BigDecimal bigDecimal = new BigDecimal(area + "").setScale(2, BigDecimal.ROUND_HALF_UP);
                        recordInfo.setArea(Float.valueOf(bigDecimal.toString()));
                        recordInfo.setDtu(dtu);
                        recordInfo.setWorkDate(date);
                        recordInfo.setCreatedTime(new Date());
                        recordList.add(recordInfo);
                    }
                    if (recordList.size() > 0) {
                        devicePcbWorkDailyRecordInfoService.saveList(recordList);
                        System.out.println("=====保存作业日报");
                    }

                    System.out.println("PCB日报生成：||||||||||||||||||||| "+DateUtils.parseDateToStr(date,DateUtils.DATE_FORMAT_YYYY_MM_DD));
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
    }
    /**
     *  每天早上3点计算前一天所有设备的面积
     * @author tm
     * @date 2023-09-08 17:42
     */
    //使用
    @Scheduled(cron = "0 0 3 * * ?")
    public void calPcbArea(){
        if(SysConfig.getJobSwitch()==0)return;
        Date date = DateUtils.addDate(new Date(),0,0,-1,0,0,0,0);
        String time = DateUtils.parseDateToStr(date,DateUtils.DATE_FORMAT_YYYYMMDD);
        PythonUtils.call(time,null,"pcb");
    }

    /**
     * 测试发送数据给粤农服
     */
    //测试
//    @Scheduled(cron = "0 */2 * * * ?")
    public void sendMessageToYueNongFu(){
        JSONObject object = new JSONObject();
        JSONObject dataObject = new JSONObject();
        dataObject.put("type","1");
        dataObject.put("device_id","11bi9900045");
        String tableName = "device_pcb_gps_info_20231017";
        GetDevicePcbGpsInfoDO getDevicePcbGpsInfoDO = new GetDevicePcbGpsInfoDO();
        getDevicePcbGpsInfoDO.setShortDtu("Y=00045");
        getDevicePcbGpsInfoDO.setSortRow("time");
        getDevicePcbGpsInfoDO.setSortOrder("asc");
        getDevicePcbGpsInfoDO.setTableName(tableName);
        List<DevicePcbGpsInfo> gpsList = devicePcbGpsInfoService.getAllList(getDevicePcbGpsInfoDO);
        if(gpsList!=null && gpsList.size()>0){
            System.out.println("定位数据条数： "+gpsList.size());
            JSONArray jsonArray = new JSONArray();
            for(DevicePcbGpsInfo info:gpsList){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("jd",info.getLon());
                jsonObject.put("wd",info.getLat());
                jsonObject.put("sbType","0");
                jsonObject.put("csType","NJJJ_ZHNL");
                jsonObject.put("gpsTime",DateUtils.parseDateToStr(info.getTime(),DateUtils.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
                jsonArray.add(jsonObject);
            }
            dataObject.put("content",jsonArray);
        }
        object.put("data",dataObject);

        System.out.println("真实数据 ：" + object.toJSONString());
        messageSenderService.sendMessage(object.toJSONString());
        System.out.println("数据发送成功");
    }

}
